import React from 'react';
import { Balloon, Button, Message } from '@teamix/ui';
import Pagination from 'components/commonPagination';
import { YunxiaoTable, ButtonIcon, YunxiaoIcon } from '@alife/devops-ui';
import exceed from 'utils/apimap';
import utils from 'utils';
import ListEmpty from 'atComponents/ListEmpty';
import RuleModal from '../newRuleModal';
import BalloonConfirm from 'components/ballonConfirm';
import Filter from './filter';
import debounce from 'lodash.debounce';
import intl from '../../../../../../../../../../../locale';

const { id: orgId } = window.FORCE.organization;
const { Tooltip } = Balloon;
const ACTION_TYPES = {
  REPO_OPERATION: intl.get({
    id: 'code-assets.sensitiveBehaviorMonitor.whitelistTable.DatabaseOperations',
    defaultMessage: '库操作',
  }),
  AUTHORITY_CHANGE: intl.get({
    id: 'code-assets.sensitiveBehaviorMonitor.whitelistTable.PermissionChange',
    defaultMessage: '权限变更',
  }),
};

export default class MonitorTable extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      tableData: [],
      isLoading: true,
      total: 0,
      page: 1,
      isModalOpen: false,
      modalData: {},
      deleting: false,
      tableParams: {},
    };

    this.getWhitelist = debounce(this.getWhitelist, 500);
  }

  componentDidMount() {
    this.getSensitiveBehaviorList(1);
  }

  getWhitelist = () => {
    this.getSensitiveBehaviorList(1);
  };

  updateWhitelistParams = (tableParams) => {
    this.setState(
      {
        tableParams,
      },

      () => {
        this.getWhitelist();
      },
    );
  };

  openModal = () => {
    this.setState({
      isModalOpen: true,
    });
  };

  closeModal = () => {
    this.setState({
      isModalOpen: false,
      modalData: {},
      type: 'new',
    });
  };

  // 获取敏感行为表
  getSensitiveBehaviorList(page) {
    const { tableParams } = this.state;
    const { users, operation_types, ...otherParams } = tableParams;
    this.setState({
      isLoading: true,
    });

    exceed
      .fetch({
        api: 'organization.grant_behavior.list',
        params: {
          orgId,
        },

        data: {
          users: users ? users.join() : '',
          operation_types: operation_types ? operation_types.join() : '',
          ...otherParams,
          page,
          per_page: 10,
        },
      })
      .then((result) => {
        const countInfo = result.shift();
        const total = countInfo.amount || 0;
        this.setState({
          tableData: result,
          isLoading: false,
          total,
          page,
        });
      })
      .fail(() => {
        this.setState({
          isLoading: false,
        });
      });
  }

  renderType = (value) => {
    // 空格隔开
    const text =
      (value &&
        value
          .map((item) => {
            return ACTION_TYPES[item];
          })
          .join('、')) ||
      '';
    return text;
  };

  renderIP = (value) => {
    const txt = value ? value.join(',') : '';
    return (
      <Tooltip trigger={<div className="table-cell-one-line">{txt}</div>} align="t" text={txt} />
    );
  };

  renderUser = (value) => {
    const nameArr = (value && value.map((item) => item.name)) || [];
    const text = nameArr.join();
    return (
      <Tooltip trigger={<div className="table-cell-one-line">{text}</div>} align="t" text={text} />
    );
  };

  onPageNoChange = (page) => {
    this.getSensitiveBehaviorList(page);
  };

  deleteProtectedBranch = (record) => {
    if (this.state.deleting) return;
    this.setState({ deleting: true });
    exceed
      .forceFetch({
        api: 'organization.grant_behavior.delete',
        params: {
          orgId,
          uuid: record.uuid,
        },
      })
      .then((result) => {
        this.setState({ deleting: false });
        if (result) {
          Message.success({
            title: intl.get({
              id: 'code-assets.sensitiveBehaviorMonitor.whitelistTable.TheWhitelistRuleHasBeen',
              defaultMessage: '白名单规则删除成功',
            }),
          });

          this.getSensitiveBehaviorList(1);
        } else {
          Message.error({
            title: intl.get({
              id: 'code-assets.sensitiveBehaviorMonitor.whitelistTable.UnableToDeleteTheWhitelist',
              defaultMessage: '白名单规则删除失败',
            }),
          });
        }
      });
  };

  render() {
    const { tableData, isLoading, total, page, isModalOpen, modalData, type, tableParams } =
      this.state;
    return (
      <div className="risk-section">
        <div className="whitelist-header">
          <div className="whitelist-header-left">
            {intl.get({
              id: 'code-assets.sensitiveBehaviorMonitor.whitelistTable.OperationsThatMeetTheWhitelist',
              defaultMessage: '满足白名单规则的操作事件将被信任，不计入敏感行为监测列表。',
            })}
          </div>
          <div className="whitelist-header-right">
            <Filter tableParams={tableParams} updateTableParams={this.updateWhitelistParams} />

            <Button
              type="primary"
              text
              onClick={() => {
                this.setState({
                  type: 'new',
                  isModalOpen: true,
                  modalData: {},
                });
              }}
              style={{ marginLeft: 12 }}
            >
              <YunxiaoIcon type="add-fill" />
              {intl.get({
                id: 'code-assets.sensitiveBehaviorMonitor.whitelistTable.CreateAWhitelistRule',
                defaultMessage: '新建白名单规则',
              })}
            </Button>
          </div>
        </div>
        <div className="whitelist-table">
          <YunxiaoTable
            hasBorder
            dataSource={tableData}
            loading={isLoading}
            emptyContent={
              <ListEmpty
                content={intl.get({
                  id: 'code-assets.sensitiveBehaviorMonitor.whitelistTable.NoData',
                  defaultMessage: '暂无数据',
                })}
                imgType="search"
                className="table-list-empty"
                size="small"
              />
            }
          >
            <YunxiaoTable.Column
              title={intl.get({
                id: 'code-assets.sensitiveBehaviorMonitor.whitelistTable.Operator',
                defaultMessage: '操作人',
              })}
              dataIndex="user_details"
              cell={this.renderUser}
            />

            <YunxiaoTable.Column
              title={intl.get({
                id: 'code-assets.sensitiveBehaviorMonitor.whitelistTable.SourceIpAddress',
                defaultMessage: '来源 IP',
              })}
              dataIndex="ips"
              width={200}
              cell={this.renderIP}
            />

            <YunxiaoTable.Column
              title={
                <div>
                  {intl.get({
                    id: 'code-assets.sensitiveBehaviorMonitor.whitelistTable.OperationType',
                    defaultMessage: '操作类型',
                  })}

                  <Balloon.Tooltip
                    trigger={
                      <ButtonIcon
                        name="question-line"
                        style={{ marginLeft: 4, display: 'inline-block' }}
                      />
                    }
                    align="t"
                  >
                    <div>
                      {intl.get({
                        id: 'code-assets.sensitiveBehaviorMonitor.whitelistTable.PermissionChangeChangeTheRoles',
                        defaultMessage: '权限变更：变更企业管理员/拥有者、变更库成员角色',
                      })}

                      <br />
                      {intl.get({
                        id: 'code-assets.sensitiveBehaviorMonitor.whitelistTable.DatabaseOperationsPullingALarge',
                        defaultMessage: '库操作：大量拉取、异常删库',
                      })}
                    </div>
                  </Balloon.Tooltip>
                </div>
              }
              dataIndex="operation_types"
              cell={this.renderType}
            />

            <YunxiaoTable.Column
              title={intl.get({
                id: 'code-assets.sensitiveBehaviorMonitor.whitelistTable.RuleUpdateTime',
                defaultMessage: '规则更新时间',
              })}
              dataIndex="gmt_modified"
              cell={utils.getBeautyTime}
              width={280}
            />

            <YunxiaoTable.Column
              title={intl.get({
                id: 'code-assets.sensitiveBehaviorMonitor.whitelistTable.Operation',
                defaultMessage: '操作',
              })}
              dataIndex="actions"
              cell={(value, index, record) => {
                return (
                  <div>
                    <Button
                      style={{ marginRight: '8px' }}
                      type="primary"
                      text
                      onClick={() => {
                        this.setState({
                          modalData: record,
                          type: 'edit',
                          isModalOpen: true,
                        });
                      }}
                    >
                      {intl.get({
                        id: 'code-assets.sensitiveBehaviorMonitor.whitelistTable.Editing',
                        defaultMessage: '编辑',
                      })}
                    </Button>
                    <BalloonConfirm
                      type="warning"
                      align="br"
                      title={'确定删除？'}
                      content={intl.get({
                        id: 'code-assets.sensitiveBehaviorMonitor.whitelistTable.AreYouSureYouWant',
                        defaultMessage: '确定要删除当前白名单规则吗？',
                      })}
                      triggerType="click"
                      trigger={
                        <Button type="primary" text>
                          {intl.get({
                            id: 'code-assets.sensitiveBehaviorMonitor.whitelistTable.Delete',
                            defaultMessage: '删除',
                          })}
                        </Button>
                      }
                      okFn={() => {
                        this.deleteProtectedBranch(record);
                      }}
                    />
                  </div>
                );
              }}
              width={120}
            />
          </YunxiaoTable>
          <Pagination onChange={this.onPageNoChange} current={page} total={total} noBorderTop />
        </div>

        {isModalOpen && (
          <RuleModal
            isModalOpen={isModalOpen}
            type={type}
            onClose={this.closeModal}
            data={{
              allowed_ip_list: modalData.ips ? modalData.ips.join() : '',
              users: modalData.user_details || [],
              operation_types: modalData.operation_types || [],
              uuid: modalData.uuid || '',
            }}
            onOk={() => {
              this.getSensitiveBehaviorList(1);
            }}
          />
        )}
      </div>
    );
  }
}
